package com.jvm.shk;

/**
 * @author ：qs
 * @date ：Created in 2022/9/24
 * @description：
 * @modified By：
 */

import java.util.Map;
import java.util.Set;

/**
 * 启动两个线程，两个线程互相抢占资源；造成死锁
 */
public class ThreadDeadLock {

    public static void main(String[] args) throws InterruptedException {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();

        new Thread(() -> {
            synchronized (s1){
                s1.append("a");
                s2.append("1");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (s2){
                    s1.append("b");
                    s2.append("2");

                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }).start();


        new Thread(() -> {
            synchronized (s2){
                s1.append("c");
                s2.append("3");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (s1){
                    s1.append("d");
                    s2.append("4");

                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
        }).start();

        Thread.sleep(200);

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 追踪当前进程中的所有线程
                Map<Thread, StackTraceElement[]> all = Thread.getAllStackTraces();
                Set<Map.Entry<Thread, StackTraceElement[]>> entries = all.entrySet();
                for (Map.Entry<Thread, StackTraceElement[]> en: entries){
                    Thread t = en.getKey();
                    StackTraceElement[] v = en.getValue();
                    System.out.println("【Thread name is ：" + t.getName() + "】");
                    for (StackTraceElement s:v){
                        System.out.println("\t" + s.toString());
                    }
                }
            }
        }).start();


    }
}
